﻿using System.Data.Linq;
using System.Data.Linq.Mapping;
using SpectrumAnalyser.Data.Common.Contracts;

namespace SpectrumAnalyser.Data.Common
{
    public class DbManagerBase : DataContext, IDbManager
    {
        public DbManagerBase(string connectionString)
            : base(connectionString)
        {

        }

        public DbManagerBase(string connectionString, MappingSource mappingSource)
            : base(connectionString, mappingSource)
        {
        }

        public TEntity Detach<TEntity>(
            TEntity entity) where TEntity : class, new()
        {
            if (entity == null)
                return null;

            //create a copy of the entity
            object Copy = new TEntity();

            //enumerate the data member mappings for the entity type
            foreach (MetaDataMember member in Mapping.GetMetaType(typeof (TEntity)).DataMembers)
            {
                if (member.IsAssociation //skip associations and deferred members
                    || member.IsDeferred)
                    continue;

                //copy the member value
                member.StorageAccessor.SetBoxedValue(
                    ref Copy,
                    member.StorageAccessor.GetBoxedValue(entity));
            }

            return (TEntity) Copy;
        }
    }
}